package org.dromara.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.dromara.admin.constant.HouseGlobalConstant;
import org.dromara.admin.enums.AuditStatus;
import org.dromara.common.core.constant.SystemConstants;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.mybatis.helper.DataPermissionHelper;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.SysUserRole;
import org.dromara.system.domain.bo.SysUserBo;
import org.dromara.system.domain.bo.SysUserPasswordBo;
import org.dromara.system.domain.bo.SysUserProfileBo;
import org.dromara.system.domain.vo.SysOssVo;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.dromara.admin.domain.bo.UserDetailBo;
import org.dromara.admin.domain.vo.UserDetailVo;
import org.dromara.admin.domain.UserDetail;
import org.dromara.admin.mapper.UserDetailMapper;
import org.dromara.admin.service.IUserDetailService;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 用户详细Service业务层处理
 *
 * @author Lion Li
 * @date 2025-09-01
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class UserDetailServiceImpl implements IUserDetailService {

    private final UserDetailMapper baseMapper;

    @Lazy
    @Autowired
    ISysUserService userService;

    /**
     * 查询用户详细
     *
     * @param userId 主键
     * @return 用户详细
     */
    @Override
    public UserDetailVo queryById(Long userId) {
        if (userId == null) {
            return null;
        }
        // 使用MPJBaseMapper进行联表查询用户信息sys_user
        MPJLambdaWrapper<UserDetail> wrapper = new MPJLambdaWrapper<UserDetail>()
            .selectAll(UserDetail.class)//查询user表全部字段
            .select(SysUser::getUserName, SysUser::getNickName, SysUser::getPhonenumber) // 只选需要的
            .eq(UserDetail::getUserId, userId)
            .leftJoin(SysUser.class, SysUser::getUserId, UserDetail::getUserId);
        UserDetailVo userDetailVo = baseMapper.selectJoinOne(UserDetailVo.class, wrapper);
        if (BeanUtil.isEmpty(userDetailVo)) {
            throw new ServiceException("用户不存在");
        }
        return userDetailVo;
    }

    /**
     * 分页查询用户详细列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 用户详细分页列表
     */
    @Override
    public TableDataInfo<UserDetailVo> queryPageList(UserDetailBo bo, PageQuery pageQuery) {
        // 使用MPJBaseMapper进行联表查询用户信息sys_user
        MPJLambdaWrapper<UserDetail> wrapper = getUserDetailMPJLambdaWrapper(bo);
        Page<UserDetailVo> result = baseMapper.selectJoinPage(pageQuery.build(), UserDetailVo.class, wrapper);
        return TableDataInfo.build(result);
    }

    /**
     * 分页查询租户列表
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return
     */
    @Override
    public TableDataInfo<UserDetailVo> queryPageTenantList(UserDetailBo bo, PageQuery pageQuery) {
        // 使用MPJBaseMapper进行联表查询用户信息sys_user
        MPJLambdaWrapper<UserDetail> wrapper = getUserDetailMPJLambdaWrapper(bo);
        wrapper.isNull(UserDetail::getRoleKey);
        Page<UserDetailVo> result = baseMapper.selectJoinPage(pageQuery.build(), UserDetailVo.class, wrapper);
        return TableDataInfo.build(result);
    }

    /***
     * UserDetail和SysUser的关联条件
     * @param bo
     * @return
     */
    private static MPJLambdaWrapper<UserDetail> getUserDetailMPJLambdaWrapper(UserDetailBo bo) {
        MPJLambdaWrapper<UserDetail> wrapper = new MPJLambdaWrapper<UserDetail>()
            .selectAll(UserDetail.class)//查询user表全部字段
            .select(SysUser::getUserName, SysUser::getPhonenumber, SysUser::getNickName) // 只选需要的
            .leftJoin(SysUser.class, SysUser::getUserId, UserDetail::getUserId)
            .orderByDesc(UserDetail::getCreateTime)
            .eq(bo.getRoleKey() != null, UserDetail::getRoleKey, bo.getRoleKey())
            .eq(bo.getLessorId() != null, UserDetail::getLessorId, bo.getLessorId()) // 查询指定房东的
            .like(StrUtil.isNotBlank(bo.getRealName()), UserDetail::getRealName, bo.getRealName()) // 模糊搜索真实姓名
            .like(StrUtil.isNotBlank(bo.getIdentityCard()), UserDetail::getIdentityCard, bo.getIdentityCard()) // 模糊搜索身份证号
            .like(StrUtil.isNotBlank(bo.getNickName()), SysUser::getNickName, bo.getNickName()) // 模糊搜索昵称
            .like(StrUtil.isNotBlank(bo.getPhonenumber()), SysUser::getPhonenumber, bo.getPhonenumber()) // 模糊搜索手机号
            .like(StrUtil.isNotBlank(bo.getOpenidWx()), UserDetail::getOpenidWx, bo.getOpenidWx()) // 模糊搜索微信openid
            .like(StrUtil.isNotBlank(bo.getOpenidAli()), UserDetail::getOpenidAli, bo.getOpenidAli()); // 模糊搜索支付宝openid
        return wrapper;
    }

    /**
     * 查询符合条件的用户详细列表
     *
     * @param bo 查询条件
     * @return 用户详细列表
     */
    @Override
    public List<UserDetailVo> queryList(UserDetailBo bo) {
        LambdaQueryWrapper<UserDetail> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<UserDetail> buildQueryWrapper(UserDetailBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<UserDetail> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(UserDetail::getUserId);
        lqw.like(StringUtils.isNotBlank(bo.getRealName()), UserDetail::getRealName, bo.getRealName());
        lqw.eq(StringUtils.isNotBlank(bo.getIdentityCard()), UserDetail::getIdentityCard, bo.getIdentityCard());
        lqw.eq(StringUtils.isNotBlank(bo.getOpenidWx()), UserDetail::getOpenidWx, bo.getOpenidWx());
        lqw.eq(StringUtils.isNotBlank(bo.getOpenidAli()), UserDetail::getOpenidAli, bo.getOpenidAli());
        lqw.eq(StringUtils.isNotBlank(bo.getAvatar()), UserDetail::getAvatar, bo.getAvatar());
        lqw.eq(StringUtils.isNotBlank(bo.getOpenAccount()), UserDetail::getOpenAccount, bo.getOpenAccount());
        return lqw;
    }

    /**
     * 新增用户详细
     *
     * @param bo 用户详细
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(UserDetailBo bo) {
        UserDetail add = MapstructUtils.convert(bo, UserDetail.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setUserId(add.getUserId());
        }
        return flag;
    }

    /**
     * 修改用户详细
     *
     * @param bo 用户详细
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(UserDetailBo bo) {
        UserDetail update = MapstructUtils.convert(bo, UserDetail.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(UserDetail entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除用户详细信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Long[] ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        userService.deleteUserByIds(ids);
        boolean b = baseMapper.deleteByIds(List.of(ids)) > 0;
        if (!b) {
            throw new ServiceException("删除用户详情失败！");
        }
        return Boolean.TRUE;
    }

    /**
     * 用户注销账号
     * @param userId 用户ID
     * @return
     */
    @Override
    public Boolean removeAccount(Long userId) {
        Long[] ids = new Long[]{userId}; // 转为数组
        userService.deleteUserByIds(ids);
        boolean b = baseMapper.deleteByIds(List.of(ids)) > 0;
        if (!b) {
            throw new ServiceException("删除用户详情失败！");
        }
        return Boolean.TRUE;
    }

    /**
     * 根据注册信息添加详情信息
     *
     * @param sysUser 注册信息
     * @return 注册用户
     */
    @Override
    public UserDetailBo insertByRegisterBody(SysUserBo sysUser) {
        UserDetailBo userDetailBo = new UserDetailBo();
        userDetailBo.setUserId(sysUser.getUserId());
        userDetailBo.setAvatar(HouseGlobalConstant.DEFAULT_AVATAR);
        userDetailBo.setRoleKey(sysUser.getRoleKey());
        userDetailBo.setRealName(sysUser.getRealName());
        userDetailBo.setIdentityCard(sysUser.getIdentityCard());
        userDetailBo.setCompanyName(sysUser.getCompanyName());
        userDetailBo.setCompanyCreditCode(sysUser.getCompanyCreditCode());
        userDetailBo.setBankName(sysUser.getBankName());
        userDetailBo.setRemitAccount(sysUser.getRemitAccount());
        userDetailBo.setDiscountRate(sysUser.getDiscountRate());
        if (sysUser.getLessorId() != null) {
            userDetailBo.setLessorId(sysUser.getLessorId());
        }
        insertByBo(userDetailBo);
        return userDetailBo;
    }

    /**
     * 切换用户账本状态
     *
     * @param userId 用户ID
     * @return
     */
    @Override
    public Boolean toggleAccountStatus(Long userId) {
        UserDetailVo userDetailVo = queryById(userId);
        if (BeanUtil.isEmpty(userDetailVo)) {
            throw new ServiceException("用户信息不存在");
        }
        userDetailVo.setOpenAccount(AuditStatus.Y.getCode().equals(userDetailVo.getOpenAccount()) ? AuditStatus.N.getCode() : AuditStatus.Y.getCode());
        return updateByBo(BeanUtil.copyProperties(userDetailVo, UserDetailBo.class));
    }

    /**
     * 根据支付宝OpenId查询用户
     *
     * @param nickName     昵称
     * @param phone        手机号
     * @param alipayOpenId 支付宝OpenId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserDetailBo selectUserByAlipayOpenId(String nickName, String phone, String alipayOpenId) {
        // 根据支付宝OpenId查询用户
        LambdaQueryWrapper<UserDetail> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UserDetail::getOpenidAli, alipayOpenId);
        UserDetail userDetail = baseMapper.selectOne(lqw);
        UserDetailBo userDetailBo = new UserDetailBo();
        // 用户不存在创建账号
        if (BeanUtil.isEmpty(userDetail)) {
            // 创建系统用户sys_user
            SysUser sysUser = userService.insertUserByAli(nickName, phone);

            // 创建用户详细
            userDetailBo.setCreateBy(666L);
            userDetailBo.setUpdateBy(666L);
            userDetailBo.setUserId(sysUser.getUserId());
            userDetailBo.setOpenidAli(alipayOpenId);
            userDetailBo.setAvatar(HouseGlobalConstant.DEFAULT_AVATAR);
            Boolean b = insertByBo(userDetailBo);
            if (!b) {
                throw new ServiceException("支付宝用户注册账号详情失败！");
            }
            return userDetailBo;
        }
        BeanUtil.copyProperties(userDetail, userDetailBo);
        return userDetailBo;
    }

    /**
     * 重置用户密码
     *
     * @param userId   用户ID
     * @param password 密码
     * @return
     */
    @Override
    public int resetUserPwd(Long userId, String password) {
        userService.checkUserAllowed(userId);
        // 调用系统服务重置用户密码
        return userService.resetUserPwd(userId, password);
    }

    /**
     * 修改用户头像
     *
     * @param userId 用户ID
     * @param oss    文件信息
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateUserAvatar(Long userId, SysOssVo oss) {
        // 忽略数据权限-修改系统表
        boolean updateSuccess = DataPermissionHelper.ignore(
            () -> userService.updateUserAvatar(userId, oss.getOssId()));
        if (!updateSuccess) {
            throw new ServiceException("修改头像存储系统表异常，请联系管理员！");
        }
        // 更换userDetail表中的头像url
        boolean updateDetail = baseMapper.update(new LambdaUpdateWrapper<UserDetail>()
            .set(UserDetail::getAvatar, oss.getUrl())
            .eq(UserDetail::getUserId, userId)) > 0;
        if (!updateDetail) {
            throw new ServiceException("修改头像存储详情表异常，请联系管理员！");
        }
        return Boolean.TRUE;
    }

    /**
     * 修改用户基本信息(sys_user表)
     * @param profile 用户信息
     * @return
     */
    @Override
    public int updateProfile(SysUserProfileBo profile) {
        SysUserBo user = BeanUtil.toBean(profile, SysUserBo.class);
        user.setUserId(LoginHelper.getUserId());
        String username = LoginHelper.getUsername();
        if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            throw new ServiceException("修改用户'" + username + "'失败，手机号码已存在");
        }
        if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            throw new ServiceException("修改用户'" + username + "'失败，邮箱账号已存在");
        }
        return DataPermissionHelper.ignore(() -> userService.updateUserProfile(user));
    }

    /**
     * 校验登录用户是否实名认证
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public Boolean isRealName(Long userId) {
        // 个人详情有身份证号码就是实名了
        UserDetailVo userDetailVo = this.queryById(userId);
        if (StrUtil.isEmpty(userDetailVo.getIdentityCard())) {
            throw new ServiceException("用户未实名认证！");
        }
        return Boolean.TRUE;
    }

    /**
     * 修改用户状态
     *
     * @param userId 用户ID
     * @return
     */
    @Override
    public int updateUserStatus(Long userId) {
        SysUserVo sysUserVo = userService.selectUserById(userId);
        if (BeanUtil.isEmpty(sysUserVo)) {
            throw new ServiceException("用户信息不存在！");
        }
        sysUserVo.setStatus(SystemConstants.NORMAL.equals(sysUserVo.getStatus()) ? SystemConstants.DISABLE : SystemConstants.NORMAL);
        return DataPermissionHelper.ignore(() -> userService.updateUserStatus(userId, sysUserVo.getStatus()));
    }

    /**
     * 资方提现后修改用户余额
     *
     * @param userId  用户ID
     * @param balance 金额
     * @return
     */
    @Override
    public Boolean updateBalance(Long userId, BigDecimal balance) {
        UserDetailVo userDetailVo = this.queryById(userId);
        if (BeanUtil.isEmpty(userDetailVo)) {
            throw new ServiceException("用户信息不存在！");
        }
        balance = balance.add(userDetailVo.getCapitalBalance());
        return baseMapper.update(new LambdaUpdateWrapper<UserDetail>()
            .set(UserDetail::getCapitalBalance, balance)
            .eq(UserDetail::getUserId, userId)) > 0;
    }
}
